<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class FileUpload extends Model
{
    private $conf = [];
    public function make(\Illuminate\Http\Request $request, $key) {
        if (!$request->hasFile($key)) {
            return [
                    'status'    => 0,
                    'info'      => '没有上传文件'
                ];
        }
        $file = $request->file($key);
        if ($file->getSize() > 3 * 1024 *1024) {
            return [
                'status'        => 0,
                'info'          => "上传文件超过3M"
            ];
        }
        if (!in_array($file->getMimeType(), config('global.site.filetype'))) {
            return [
                'status'        => 0,
                'info'          => '上传文件类型不允许'
            ];
        }
        $this->conf($file);
        $file->move($this->moveDirectory(), $this->moveFileName());
        return $this->webFileName();
    }
    /**
     * 
     * @param type $file
     */
    public function conf($file) {
        $this->conf = [
            'date'  =>  date("Ymd"),
            'rand'  =>  time() . rand(1000, 9999),
            'dir'   =>  'card',
            'extend'=>  $file->guessExtension()
        ];
    }
    /**
     * 
     * @return type
     */
    public function moveDirectory() {
        return dirname(app_path())."/public/upload/{$this->conf['dir']}/{$this->conf['date']}";
    }
    
    /**
     * 
     * @return type
     */
    public function moveFileName() {
        return implode('.', [$this->conf['rand'], $this->conf['extend']]);
    }
    
    /**
     * 
     */
    public function webFileName() {
        return "/upload/{$this->conf['dir']}/{$this->conf['date']}/".$this->moveFileName();
    }
}
